package com.spring.shops.service.impl;

import com.spring.shops.dao.TzAreaMapper;
import com.spring.shops.model.entity.TzArea;
import com.spring.shops.model.result.ServerResponseEntityVoid;
import com.spring.shops.model.vo.AreaVO;
import com.spring.shops.service.AreaService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AreaServiceImpl implements AreaService {
    @Autowired
    private TzAreaMapper mapper;
    /**
     * 递归获取所有的省县区
     * @param pid
     * @return
     */
    @Override
    public ServerResponseEntityVoid<List<TzArea>> getArea(String pid){
        //查询所有parant_id=0的数据
        Long parentId= Long.valueOf(pid);
        List<TzArea> list=mapper.selectByParantId(parentId);
        return ServerResponseEntityVoid.success(list);
    }
    /**
     * 列出所有的地区
     */
    @Override
    public ServerResponseEntityVoid<List<AreaVO>> list() {
        List<TzArea> areaList=mapper.selectAll();
        List<AreaVO> areaListVO=new ArrayList<>();
        //进行属性拷贝
        for (TzArea area : areaList) {
            areaListVO.add(new AreaVO(
                    area.getAreaId(), area.getAreaName(), area.getParentId(), area.getLevel(),null
            ));
        }
        return ServerResponseEntityVoid.success(areaListVO);
    }
    /**
     * 新增数据
     * @param area
     * @return
     */
    @Override
    public ServerResponseEntityVoid save(TzArea area) {
       //直接插入数据库(先获取它的父类的级别）
        Long parentId = area.getParentId();
        TzArea parentArea=mapper.selectById(parentId);
        area.setLevel(parentArea.getLevel());
        int rows=mapper.insert(area);
        if(rows>0){
            return ServerResponseEntityVoid.success();
        }else return ServerResponseEntityVoid.error();
    }

    /**
     * 根据id删除数据
     * @param id
     * @return
     */
    @Override
    public ServerResponseEntityVoid deleteById(Long id) {
        int rows=mapper.deleteById(id);
        if(rows>0){
            return ServerResponseEntityVoid.success();
        }else return ServerResponseEntityVoid.error();
    }
    /**
     * 根据id获取信息
     * @param id
     * @return
     */
    @Override
    public ServerResponseEntityVoid<AreaVO> getInfoById(Long id) {
        TzArea tzArea = mapper.selectById(id);
        //属性拷贝
        AreaVO areaVO = new AreaVO();
        BeanUtils.copyProperties(tzArea,areaVO);
        return ServerResponseEntityVoid.success(areaVO);
    }
    /**
     * 更新数据
     * @param vo
     * @return
     */
    @Override
    public ServerResponseEntityVoid updateInfo(AreaVO vo) {
        TzArea tzArea = new TzArea();
        BeanUtils.copyProperties(vo,tzArea);
        int rows = mapper.updateByPrimaryKey(tzArea);
        if(rows>0){
            return ServerResponseEntityVoid.success();
        }else return ServerResponseEntityVoid.error();
    }
}

